<template>
  <div>
    <div style="margin-bottom:15px">模板基本信息</div>
    <el-form
      ref="queryForm"
      :model="queryForm"
      :rules="rules"
      label-width="90px"
      size="mini"
      class="bg-white"
      label-position="right"
    >
      <el-row :gutter="10">
        <el-col :span="10" :offset='1'>
          <el-form-item label="模板名称：" prop="templateName">
            <el-input
              v-if="!isRead"
              v-model="queryForm.templateName"
              style="width:100%"
              type="text"
              placeholder="请输入模板名称"
              maxlength="50"
              size="small"
            />
            <span v-if="isRead">{{ queryForm.templateName }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10" :offset='1'>
          <el-form-item
              :label="'年级:'"
              prop="year"
          >
              <el-date-picker
                  v-if="!isRead"
                  v-model="queryForm.year"
                  :placeholder="$t('message.plsSelect')"
                  type="year"
                  size="small"
                  value-format="yyyy"
                  style="width: 100%;"
              />
              <span v-if="isRead">{{ queryForm.year }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10" :offset='1'>
          <el-form-item label="培养层次：" prop="trainingLevel">
            <el-select
              v-if="!isRead"
              v-model="queryForm.trainingLevel"
              style="width:100%"
              size="small"
            >
              <el-option
                v-for="item in options.trainingLevel"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-if="isRead">
              {{
              getTrainingLevelLabelByValue(queryForm.trainingLevel)
              }}
            </span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10" :offset='1'>
          <el-form-item label="类别：" prop="professionCateGory">
            <el-select
              v-if="!isRead"
              v-model="queryForm.professionCateGory"
              style="width:100%"
              size="small"
            >
              <el-option
                v-for="item in options.category"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-if="isRead">
              {{
              getCategoryLabelByValue(queryForm.professionCateGory)
              }}
            </span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10" :offset='1'>
          <el-form-item label="学期数：" prop="schoolTerm">
            <el-select
              v-if="!isRead"
              v-model="queryForm.schoolTerm"
              style="width:100%"
              size="small"
            >
              <el-option
                v-for="item in options.schoolTerm"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span v-if="isRead">
              {{
              queryForm.schoolTerm
              }}
            </span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <el-row>
      <el-col :span='4'>
        <div>章节划分</div>
      </el-col>
      <el-col :span='2' class="float-right" style="margin-bottom:15px">
        <el-button size="mini" @click="addRow()">添加</el-button>
      </el-col>
    </el-row>
    <el-table :data="chapters" size="mini" tooltip-effect="light">
      <el-table-column prop="id" label="序号" width="100"/>
      <el-table-column label="章节名称" show-overflow-tooltip>
        <template slot-scope="props">
          <el-input
            v-if="props.row.id == selectChapterId || props.row.opr == 'new'"
            v-model="props.row.name"
            type="text"
            maxlength="50"
          />
          <span
            v-if="props.row.id != selectChapterId && props.row.opr == 'normal'"
          >{{ props.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="英文名称" show-overflow-tooltip>
        <template slot-scope="props">
          <el-input
            v-if="props.row.id == selectChapterId || props.row.opr == 'new'"
            v-model="props.row.nameEn"
            type="text"
            maxlength="50"
          />
          <span
            v-if="props.row.id != selectChapterId && props.row.opr == 'normal'"
          >{{ props.row.nameEn }}</span>
        </template>
      </el-table-column>
      <el-table-column label="内容导入方式">
        <template slot-scope="props">
          <el-select
            v-if="props.row.id == selectChapterId || props.row.opr == 'new'"
            v-model="props.row.contentType"
            style="width:100%"
          >
            <el-option label="直接输入" value="1"/>
            <el-option label="系统表格" value="2"/>
          </el-select>
          <span
            v-if="
              props.row.id != selectChapterId &&
                props.row.opr == 'normal' &&
                props.row.contentType == 1
            "
          >直接输入</span>
          <span
            v-if="
              props.row.id != selectChapterId &&
                props.row.opr == 'normal' &&
                props.row.contentType == 2
            "
          >系统表格</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="排序序号" width="100">
        <template slot-scope="props">
          <el-input
            v-if="props.row.id == selectChapterId || props.row.opr == 'new'"
            v-model="props.row.sortNo"
            type="text"
          />
          <span
            v-if="props.row.id != selectChapterId && props.row.opr == 'normal'"
          >{{ props.row.sortNo }}</span>
        </template>
      </el-table-column> -->
      <el-table-column v-if="!isRead" label="操作" align='center'>
        <template slot-scope="props">
          <el-button
            v-if="props.row.opr == 'normal' && props.row.id != selectChapterId"
            type="text"
            size="mini"
            @click="editRow(props.row)"
          >编辑</el-button>
          <el-button
            v-if="(props.row.opr == 'new'&&props.row.name)||(props.row.opr == 'normal' && props.row.id != selectChapterId)"
            type="text"
            size="mini"
            @click="removeRow(props.row)"
          >删除</el-button>
          <el-button
            v-if="props.row.opr == 'normal' && props.row.id == selectChapterId"
            type="text"
            size="mini"
            @click="saveRow(props.row)"
          >保存</el-button>
          <el-button
            v-if="props.row.opr == 'normal' && props.row.id == selectChapterId"
            type="text"
            size="mini"
            @click="cancelRow(props.row)"
          >取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row class="pd-12px float-right">
      <el-col :span="24">
        <el-button size="medium" @click="back">返回</el-button>
        <el-button v-if="!isRead" size="medium" @click="submit">保存</el-button>
        <el-button size="medium" type="primary" @click="nextStep">下一步</el-button>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import Constant from "common/src/utils/constant";
import { queryDic, findTrainingLevelByProjId } from "common/src/api/dictionary";
import {
  saveCultureTemplate,
  getCultureTemplateById
} from "common/src/api/culture/bachelor";
import Bus from "common/src/utils/bus";
import { mapActions } from "vuex";
const ROW_TYPE = {
  NORMAL: "normal",
  NEW: "new"
};
export default {
  name: "template-base-info",
  props: {
    next: {
      type: Function,
      default: null
    },
    templateId: {
      type: String,
      default: null
    },
    isRead: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      queryForm: {
        "x-token": "",
        templateName: "",
        year: "",
        trainingLevel: "",
        professionCateGory: "",
        schoolTerm:"",
        font: "",
        fontSize: 14
      },
      options: {
        year: [],
        trainingLevel: [],
        schoolTerm:[],
        category: []
      },
      chapters: [],
      newChapters:[],
      selectChapterId: 0,
      currentDeleteId: 0,
      rules: {
        templateName: [
          {
            required: true,
            message: "请填写模板名称",
            trigger: "blur"
          }
        ],
        year: [
          {
            required: true,
            message: "请选择年级",
            trigger: "blur"
          }
        ],
        trainingLevel: [
          {
            required: true,
            message: "请选择培养层次",
            trigger: "change"
          }
        ],
        professionCateGory: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change"
          }
        ],
        schoolTerm: [
          {
            required: true,
            message: "请选择学期数",
            trigger: "change"
          }
        ],
      }
    };
  },
  mounted() {
    this.init();
  },
  created() {},
  methods: {
    ...mapActions(["delTab"]),
    init() {
      this.options.category = [];
      this.options.trainingLevel = [];
      this.queryForm["x-token"] =
        this.$store.state.session.sessionid ||
        localStorage.getItem("sessionid") ||
        "";
      // 绑定年级
      const now = new Date();
      const currentYear = now.getFullYear();

      const minYear = currentYear - 5;
      for (let year = currentYear; year > minYear; year--) {
        const obj = { label: year, value: year };
        this.options.year.push(obj);
      }
      const schoolTerm = 20; 
      for (let i = 0; i < schoolTerm; i++) {
        const obj = { label: i+1, value: i+1 };
        this.options.schoolTerm.push(obj);
      }
      // 绑定培养层次
      const data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_PYCC"]
      };
      this.options.category.push({
        label: this.$t("culture.profession.bigProfession"),
        value: "1"
      });
      this.options.category.push({
        label: this.$t("culture.profession.profession"),
        value: "2"
      });
      findTrainingLevelByProjId(this.$route.params.projId).then(res => {
        if (res.code === 200) {
          this.loadTrainingLevelOptions("trainingLevel", res.data);
          if (this.templateId) {
            this.getTemplateInfo(this.templateId);
          } else {
            this.appendCreateRow();
          }
        }
      });
      // 使用默认
      this.queryForm.font = Constant.cultureTemplateChapter.font;
      this.queryForm.fontSize = Constant.cultureTemplateChapter.fontSize;
    },
    loadTrainingLevelOptions(optionKey, dataObj) {
      _.each(dataObj, level => {
        this.options[optionKey].push({
          label:
            "en" === this.$store.getters.language ? level.nameEN : level.nameCN,
          value: level.code
        });
      });
    },
    // 获取模板信息
    getTemplateInfo(id) {
      getCultureTemplateById(id).then(response => {
        if (response.code === 200) {
          this.queryForm.templateName = response.data.name;
          this.queryForm.year = response.data.year+'';
          this.queryForm.trainingLevel = response.data.trainingLevel;
          this.queryForm.formLearning = response.data.formLearning;
          this.queryForm.schoolTerm = response.data.schoolTerm;
          this.queryForm.font = response.data.font;
          this.queryForm.fontSize = response.data.fontSize;
          this.queryForm.professionCateGory = response.data.professionCateGory;
          const chapters = [];
          if (response.data.sonCultureTemplateList.length > 0) {
            response.data.sonCultureTemplateList.forEach((row, index) => {
              chapters.push({
                id: index + 1,
                name: row.name,
                nameEn: row.nameEn,
                //sortNo: row.sortNo,
                contentType: row.contentType ? row.contentType.toString() : "",
                opr: ROW_TYPE.NORMAL,
                font: row.font,
                fontSize: row.fontSize,
                realId: row.id
              });
            });
          }
          this.chapters = chapters;
          this.appendCreateRow();
        }
      });
    },
    // 新增
    addRow() {
      let len=this.chapters.length;
      
      console.log('id',this.templateId);
      
      let row=this.chapters.filter((item,index)=>{
         return index==len-1
      })
     row.forEach((item)=>{
       if (item.name.trim() == "") {
          this.$message({
            type: "info",
            message: "请填写章节名称"
          });
          return;
        }
        // item.opr = ROW_TYPE.NORMAL;
         this.appendCreateRow();
      })
      
      // this.appendCreateRow();
    },
    editRow(row) {
      this.selectChapterId = row.id;
      this.newChapters = _.cloneDeep(this.chapters);
    },
    removeRow(row) {
      if(row.name.trim() == ""){
        return;
      }
      this.$confirm("是否删除该章节?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.currentDeleteId = row.id;
          this.confirmDelete();
        })
        .catch(e => {});
    },
    saveRow(){
      this.selectChapterId = 0;
    },
    cancelRow(row) {
      this.chapters = this.newChapters
      this.selectChapterId = 0;
    },
    // 添加新增行
    appendCreateRow() {
      if (!this.isRead) {
        const row = {
          id: "",
          name: "",
          nameEn: "",
          //sortNo: "",
          contentType: "1",
          fontSize: this.queryForm.fontSize,
          font: this.queryForm.font,
          opr: ROW_TYPE.NEW
        };
        if (this.chapters.length == 0) {
          row.id = 1;
          //row.sortNo = 1;
        } else {
          const maxObject = _.maxBy(this.chapters, c => c.id);
          row.id = parseInt(maxObject.id) + 1;
          //row.sortNo = row.id;
        }
        this.chapters.push(row);
      }
    },
    // 删除当前行，重新设置序号,排除新增行
    confirmDelete() {
      const newChapters = _.cloneDeep(this.chapters);
      _.remove(newChapters, c => c.id == this.currentDeleteId);
      newChapters.forEach((c, index) => {
        if (c.id) {
          c.id = parseInt(index) + 1;
        }
        if (c.opr == ROW_TYPE.NEW) {
          //c.sortNo = c.id;
        }
      });

      this.chapters = newChapters;
    },
    // 返回
    back() {
      Bus.$emit("selectCultureTemplate");
      this.delTab("/cultureTemplateDetail");
      window.history.back();
    },
    isValid() {
      let result = true;
      let msg = "";
      const reg = new RegExp(/^\d+$/);
      this.chapters.forEach(c => {
        if (
          result &&
          (c.opr == ROW_TYPE.NORMAL ||
            (c.opr == ROW_TYPE.NEW && c.name.trim() != ""))
        ) {
          if (c.name.trim() == "") {
            result = false;
            msg = "章节名称不能为空";
          } 
          // else if (
          //   c.sortNo == null ||
          //   c.sortNo.toString().trim() == "" ||
          //   !reg.test(c.sortNo.toString().trim())
          // ) {
          //   result = false;
          //   msg = "章节排序序号必须是数字";
          // }
        }
      });
      if (!result) {
        this.$message({
          type: "info",
          message: msg
        });
      }
      return result;
    },
    // 保存
    submit() {
      this.$refs.queryForm.validate(valid => {
        if (!valid) {
          return;
        }
        if (!this.isValid()) {
          return;
        }
        // 移除空的新增行
        const chapters = this.chapters.filter(
          c =>
            c.opr == ROW_TYPE.NORMAL ||
            (c.opr == ROW_TYPE.NEW && c.name.trim() != "")
        );
        if (chapters.length == 0) {
          this.$confirm("未添加章节信息，是否继续保存?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.postData();
          });
        } else {
          let containTable = false; // 导入方式是否包含表格
          chapters.forEach(c => {
            if (!containTable && c.contentType == "2") {
              containTable = true;
            }
          });
          if (!containTable) {
            this.$confirm("章节中不包含系统表格，是否继续保存?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.postData();
            });
          } else {
            this.postData();
          }
        }
      });
    },
    postData() {
      // 处理提交数据
      const data = {
        projId: this.$route.params.projId,
        id: this.templateId,
        year: this.queryForm.year,
        name: this.queryForm.templateName.trim(),
        trainingLevel: this.queryForm.trainingLevel,
        schoolTerm: this.queryForm.schoolTerm,
        professionCateGory: this.queryForm.professionCateGory,
        font: this.queryForm.font,
        fontSize: this.queryForm.fontSize,
        sonCultureTemplateList: []
      };
      this.chapters.forEach(c => {
        if (
          c.opr == ROW_TYPE.NORMAL ||
          (c.opr == ROW_TYPE.NEW && c.name.trim() != "")
        ) {
          const row = {
            name: c.name.trim(),
            nameEn: c.nameEn.trim(),
            //sortNo: c.sortNo.toString().trim(),
            contentType: c.contentType,
            font: c.font,
            fontSize: c.fontSize
          };
          if (c.realId) {
            row.id = c.realId;
          }
          data.sonCultureTemplateList.push(row);
        }
      });
      // 保存模板和章节信息
      saveCultureTemplate(data).then(response => {
        if (response.code === 200) {
          Bus.$emit("saveTemplate", response.data);
          this.$message({
            type: "success",
            message: "保存模板成功"
          });
          this.selectChapterId = 0;
          this.init();
        }
      });
    },
    // 下一步
    // nextStep() {
    //   if (this.next) {
    //     this.next();
    //     this.postData();
    //   }
    // },
    // getTrainingLevelLabelByValue(value) {
    //   const option = this.options.trainingLevel.find(t => t.value == value);
    //   if (option) {
    //     return option.label;
    //   } else {
    //     return "";
    //   }
    // },
    nextStep() {
      if (this.next) {
        this.$refs.queryForm.validate(valid => {
          if (!valid) {
            return;
          }
          if (!this.isValid()) {
            return;
          }
          // 移除空的新增行
          const chapters = this.chapters.filter(
            c =>
              c.opr == ROW_TYPE.NORMAL ||
              (c.opr == ROW_TYPE.NEW && c.name.trim() != "")
          );
          if (chapters.length == 0) {
            this.$confirm("未添加章节信息，是否继续保存?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(() => {
              this.postData2();
            });
          } else {
            let containTable = false; // 导入方式是否包含表格
            chapters.forEach(c => {
              if (!containTable && c.contentType == "2") {
                containTable = true;
              }
            });
            if (!containTable) {
              this.$confirm("章节中不包含系统表格，是否继续保存?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(() => {
                this.postData2();
              });
            } else {
              this.postData2();
            }
          }
        });
      }
    },
    postData2() {
      // 处理提交数据
      const data = {
        projId: this.$route.params.projId,
        id: this.templateId,
        year: this.queryForm.year,
        name: this.queryForm.templateName.trim(),
        trainingLevel: this.queryForm.trainingLevel,
        schoolTerm: this.queryForm.schoolTerm,
        professionCateGory: this.queryForm.professionCateGory,
        font: this.queryForm.font,
        fontSize: this.queryForm.fontSize,
        sonCultureTemplateList: []
      };
      this.chapters.forEach(c => {
        if (
          c.opr == ROW_TYPE.NORMAL ||
          (c.opr == ROW_TYPE.NEW && c.name.trim() != "")
        ) {
          const row = {
            name: c.name.trim(),
            nameEn: c.nameEn.trim(),
            //sortNo: c.sortNo.toString().trim(),
            contentType: c.contentType,
            font: c.font,
            fontSize: c.fontSize
          };
          if (c.realId) {
            row.id = c.realId;
          }
          data.sonCultureTemplateList.push(row);
        }
      });
      // 保存模板和章节信息
      saveCultureTemplate(data).then(response => {
        if (response.code === 200) {
          Bus.$emit("saveTemplate", response.data);
          this.$message({
            type: "success",
            message: "保存模板成功"
          });
          this.selectChapterId = 0;
          this.next();
        }
      });
    },
    getCategoryLabelByValue(value) {
      const option = this.options.category.find(f => f.value == value);
      if (option) {
        return option.label;
      } else {
        return "";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.base-title {
  border-bottom: 1px solid #cccccc;
  line-height: 30px;
  margin-bottom: 20px;
}
</style>
